<template>
  <div class="home">
    <div class="header-banner">
      <div class="banner-inner">
        <div class="banner-left">
          <div class="left-box">
            <img class="avatar" :src="userInfo.headImage" alt="avatar">
            <div class="info">
              <div class="info-title">
                {{userInfo.username}}<span>{{helloText}}！</span><img @click="toModifyInfo" src="@/common/image/icon/edit-info.png">
              </div>
              <div class="info-item" v-if="userInfo.position !== '未填写' && userInfo.company !== '未填写'">
                <img src="@/common/image/icon/icon-person.png">
                <span>{{userInfo.position}} | {{userInfo.company}}</span>
              </div>
              <div class="info-item" v-else-if="userInfo.position !== '未填写' || userInfo.company !== '未填写'">
                <img src="@/common/image/icon/icon-person.png">
                <span>{{userInfo.position === '未填写' ? userInfo.position : userInfo.company}}</span>
              </div>
              <div class="info-item" v-show="userInfo.description !== '未填写' && userInfo.description !== ''">
                <img src="@/common/image/icon/icon-profile.png">
                {{userInfo.description}}
              </div>
            </div>
          </div>
        </div>
        <div class="banner-right">
          <div class="right-box">
            <div class="quick">
              <div class="quick-title">您已创建 <span>{{totalProject}}</span> 个项目，上传 <span>{{totalDataSet}}</span> 个数据集</div>
              <div class="quick-action">
                <a @click="toCreateProject">创建项目</a>
                <span class="seperator-line"></span>
                <a @click="toAddDataSet">上传数据集</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="content-container">
        <div class="content-left">
          <div class="content-left-box">
            <div class="left-item first-task">
              <div class="item">
                <div class="item-task" @click="toProject('WAITING')">
                  <img class="avatar" src="@/common/image/icon/run-waiting.png" alt="waiting">
                  <div class="task-info">
                    <div class="task-number">{{waitCount}}</div>
                    <div class="task-des">正在等待的任务</div>
                  </div>
                </div>
              </div>
              <div class="item">
                <div class="item-task" @click="toProject('RUNNING')">
                  <img class="avatar" src="@/common/image/icon/run-running.png" alt="running">
                  <div class="task-info">
                    <div class="task-number">{{runCount}}</div>
                    <div class="task-des">正在运行的任务</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="left-item">
              <div class="item">
                <div class="item-task" @click="toProject('SUCCEEDED')">
                  <img class="avatar" src="@/common/image/icon/run-success.png" alt="stopped">
                  <div class="task-info">
                    <div class="task-number">{{successCount}}</div>
                    <div class="task-des">运行成功的任务</div>
                  </div>
                </div>
              </div>
              <div class="item">
                <div class="item-task" @click="toProject('FAILED')">
                  <img class="avatar" src="@/common/image/icon/run-fail.png" alt="successed">
                  <div class="task-info">
                    <div class="task-number">{{failCount}}</div>
                    <div class="task-des">运行失败的任务</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="left-item-bottom">
              <div class="link-doc">
                <div class="link-doc-text">如何快速创建项目，开始训练任务？</div>
                <div class="link-doc-text">如何创建数据集？</div>
                <div class="link-doc-button" @click="toDocument"><i></i>使用文档</div>
              </div>
            </div>
          </div>
        </div>
        <div class="content-right">
          <div class="content-right-box">
            <div class="right-item">
              <div class="consume-content">
                <div class="consume-content-item compute">
                  <img class="consume-img" src="@/common/image/icon/icon-suanli.png" alt="waiting">
                  <div class="consume-item-count" v-if="isOverTenThousand">可用算力 <el-tooltip :content="String(powerSurAll)" placement="top" effect="light"><span>{{ powerSur }}</span></el-tooltip></div>
                  <div class="consume-item-count" v-else>可用算力 <span>{{ powerSur }}</span></div>
                  <div class="consume-item-count-used">已使用算力 {{ powerUsed }}</div>
                  <div class="consume-item-count-link">
                    <a @click="toOrderMachine">查看算力明细</a> | <a @click="toOrder">算力充值</a>
                  </div>
                </div>
                <div class="consume-content-item storage">
                  <img class="consume-img" src="@/common/image/icon/icon-cuncu.png" alt="waiting">
                  <div class="consume-item-count">可用存储 <span>{{storageAvai}} GB</span></div>
                  <div class="consume-item-count-used">已用容量 {{ storageUsed }}GB</div>
                  <div class="consume-item-count-link"></div>
                </div>
              </div>
            </div>
            <div class="right-item">
              <a :href="communityURL" target="_blank">
                <div class="social">
                  <span>有问题，去社区跟其他朋友一起聊聊</span>
                </div>
                <!-- <img class="social-img" src="@/common/image/social.png"> -->
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getTaskStatus, getProjectList } from '@/api/project'
import { getDataSet } from '@/api/dataset'
import { getUserCalculationPower, queryStorage, getOrderStorageCountByUserId } from '@/api/order'
import { mapMutations, mapGetters } from 'vuex'
import qs from 'qs'
export default {
  data () {
    return {
      communityURL: `${process.env.VUE_APP_BITA_HOME}`,
      // 项目数
      totalProject: 0,
      // 数据集数
      totalDataSet: 0,
      // 运行任务数
      runCount: 0,
      // 等待任务数
      waitCount: 0,
      // 暂停任务数
      stopCount: 0,
      // 失败任务数
      failCount: 0,
      // 成功任务数
      successCount: 0,
      // 结束任务数
      endCount: 0,
      usedTime: 0,
      // 当前剩余机时
      curSurplus: 0,
      // 已使用机时
      curUsed: 0,
      // 已用算力
      powerUsed: 0,
      // 剩余算力
      powerSur: 0,
      powerSurAll: 0,
      isOverTenThousand: false,
      // 可用存储空间
      storageAvai: 0,
      // 已用存储空间
      storageUsed: 0,
      helloText: ''
    }
  },
  methods: {
    // 跳转帮助文档
    toDocument () {
      window.open(`${process.env.VUE_APP_HELP}/help/index.html`)
    },
    // 跳转编辑个人信息
    toModifyInfo () {
      window.open(`${process.env.VUE_APP_BITA_EDIT_INFO}?token=${this.userInfo.bitaToken}`)
    },
    // 跳转项目创建
    toCreateProject () {
      this.$router.push({ 'path': '/project/create' })
    },
    // 跳转上传数据集
    toAddDataSet () {
      this.$router.push({ 'path': '/dataset/create' })
    },
    // 跳转算力明细列表
    toOrderMachine () {
      this.$router.push({ 'path': '/order/list' })
    },
    // 跳转算力充值
    toOrder () {
      this.$router.push({ 'path': '/order' })
    },
    // 跳转任务视图
    toProject (state) {
      const obj = {
        isFromHome: true,
        state: state
      }
      this.storeTaskFromHome(obj)
      this.$router.push({ 'path': '/project/task' })
    },
    // 处理任务数据
    handleJobs (jobs) {
      this.runCount = 0
      this.waitCount = 0
      this.stopCount = 0
      this.failCount = 0
      this.successCount = 0
      this.endCount = 0
      jobs.forEach((el, i) => {
        this.usedTime = 0
        let hjss = this.getHumanizedJobStateString(jobs[i])
        if (hjss.startsWith('Running')) {
          this.runCount++
          let ru = this.getDurationInSeconds(jobs[i].createdTime, null)
          this.usedTime = this.usedTime + ru
        }
        if (hjss.startsWith('Waiting')) {
          this.waitCount++
        }
        if (hjss.startsWith('Stopped')) {
          this.stopCount++
          let ru = this.getDurationInSeconds(jobs[i].createdTime, jobs[i].completedTime)
          this.usedTime = this.usedTime + ru
        }
        if (hjss.startsWith('Failed')) {
          this.failCount++
          let ru = this.getDurationInSeconds(jobs[i].createdTime, jobs[i].completedTime)
          this.usedTime = this.usedTime + ru
        }
        if (hjss.startsWith('Succeeded')) {
          this.successCount++
          let ru = this.getDurationInSeconds(jobs[i].createdTime, jobs[i].completedTime)
          this.usedTime = this.usedTime + ru
        }
      })
      this.endCount = this.successCount
      this.stopCount = this.failCount + this.stopCount
    },
    getDurationInSeconds (startTime, endTime) {
      if (startTime === null) {
        return 0
      }
      if (endTime == null) {
        endTime = Date.now()
      }
      return Math.round(Math.max(0, endTime - startTime) / 1162)
    },
    getHumanizedJobStateString (jobInfo) {
      let hjss = ''
      if (jobInfo.state === 'JOB_NOT_FOUND') {
        hjss = 'N/A'
      } else if (jobInfo.state === 'WAITING') {
        if (jobInfo.executionType === 'STOP') {
          hjss = 'Stopping'
        } else {
          hjss = 'Waiting'
        }
      } else if (jobInfo.state === 'RUNNING') {
        if (jobInfo.executionType === 'STOP') {
          hjss = 'Stopping'
        } else {
          hjss = 'Running'
        }
      } else if (jobInfo.state === 'SUCCEEDED') {
        hjss = 'Succeeded'
      } else if (jobInfo.state === 'FAILED') {
        hjss = 'Failed'
      } else if (jobInfo.state === 'STOPPED') {
        hjss = 'Stopped'
      } else {
        hjss = 'Unknown'
      }
      return hjss
    },
    helloWord () {
      const nowTime = new Date()
      const nowHour = nowTime.getHours()
      if (nowHour < 6) {
        return '凌晨好'
      } else if (nowHour < 9) {
        return '早上好'
      } else if (nowHour < 12) {
        return '上午好'
      } else if (nowHour < 14) {
        return '中午好'
      } else if (nowHour < 17) {
        return '下午好'
      } else if (nowHour < 19) {
        return '傍晚好'
      } else if (nowHour < 22) {
        return '晚上好'
      } else {
        return '夜深了'
      }
    },
    /*
      -----接口调用-----
    */
    // 获取用户创建项目总数
    _getProjectList () {
      let query = `?cp=${1}&ps=${0}`
      this.finished = true
      getProjectList(query).then(res => {
        if (res.message.code === 0) {
          this.totalProject = res.data.total
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 获取用户创建数据集总数
    _getDataSetList () {
      let query = `?cp=${1}&ps=${0}`
      getDataSet(query).then(res => {
        if (res.message.code === 0) {
          this.totalDataSet = res.data.total
        } else {
          this.finished = true
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    _getTaskStatus () {
      getTaskStatus().then(res => {
        if (res.message.code === 0) {
          let result = res.data
          this.runCount = result.runningNum
          this.waitCount = result.waitingNum
          this.successCount = result.succeededNum
          this.failCount = result.failedNum
          this.stopCount = result.stoppedNum + result.stoppingNum ? result.stoppingNum : 0
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 查询算力和存储详情
    _getUserPowerStorage () {
      const query = `?token=${this.userInfo.bitaToken}`
      getUserCalculationPower(query).then(res => {
        if (res.code === 0) {
          this.powerUsed = res.result.used_calculation_power.toFixed(1)
          const surplus = res.result.surplusCalculationPower
          if (surplus > 10000) {
            this.isOverTenThousand = true
            this.powerSurAll = surplus.toFixed(1)
            this.powerSur = (surplus / 10000).toFixed(1) + 'W'
          } else {
            this.powerSur = surplus.toFixed(1)
          }
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
      queryStorage(query).then(res => {
        if (res.code === 0) {
          this.storageUsed = res.result.storageSize.toFixed(1)
          this._getOrderStorageCountByUserId()
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查询总存储空间
    _getOrderStorageCountByUserId () {
      const data = qs.stringify({
        token: this.userInfo.bitaToken
      })
      getOrderStorageCountByUserId(data).then(res => {
        if (res.code === 0) {
          this.storageAvai = (res.result - this.storageUsed).toFixed(1)
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    ...mapMutations({
      storeTaskFromHome: 'SET_TASK_FROM_HOME'
    })
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  mounted () {
    this._getTaskStatus()
    this._getProjectList()
    this._getDataSetList()
    this._getUserPowerStorage()
    this.helloText = this.helloWord()
  }
}
</script>

<style scoped lang="stylus" rel="stylus">
.home
  width 100%
  .header-banner
    background-color #F4F7F8
    .banner-inner
      width 100%
      display flex
      position relative
      margin 0 auto
      max-width 1162px
      height 100%
      .banner-left
        width 50%
        height 100%
        .left-box
          height 100%
          display flex
          align-items flex-start
          padding 30px 0
        .avatar
          width 56px
          height 56px
          border-radius 50%
        .info
          margin-left 30px
          .info-title
            display flex
            align-items center
            font-size 28px
            color #2D323B
            font-weight 600
            margin-bottom 17px
            height 40px
            line-height 40px
            >span
              font-size 14px
              color #6E6E6E
              font-weight normal
              padding 0 12px
            >img
              width 14px
              cursor pointer
          .info-item
            font-size 14px
            color #57606A
            display flex
            align-items center
            margin-bottom 8px
            >img
              width 16px
              margin-right 8px
      .banner-right
        width 50%
        display flex
        justify-content flex-end
        .right-box
          padding 30px 0
          .quick-title
            margin-bottom 3px
            font-size 14px
            color #6E6E6E
            height 40px
            line-height 40px
            >span
              color #49d799
          .quick-action
            text-align right
            font-size 14px
            color #007AFF
            .seperator-line
              width 2px
              height 10px
              background #8c94a0
              display inline-block
              font-size 12px
              margin 0 10px
  .content
    width 100%
    .content-container
      width 100%
      position relative
      margin 0 auto
      max-width 1162px
    .content-left
      width 50%
      display inline-block
      .content-left-box
        padding 25px 15px 25px 0
        .left-item
          width 100%
          display flex
          justify-content space-between
          margin-bottom 35px
        .item
          background #F4FAFF
          border-radius 1px
          width 266px
          border 1px solid #E5E9F0
          &:hover
            bottom 6px
            box-shadow 0 0 18px 0 #e4e7ed
        .item-task
          padding 43px 35px
          display flex
          align-items center
          cursor pointer
          box-shadow 0 0 10px 0 rgba(74,74,74,0.05)
          .avatar
            width 56px
            height 56px
        .task-info
          margin-left 15px
        .task-number
          font-size 32px
          color #24292E
          letter-spacing 0
          height 45px
          line-height 45px
        .task-des
          font-size 12px
          color #4A4A4A
          letter-spacing 0
        .left-item-bottom
          height 142px
          width 100%
          background #0093D5
          border-radius 1px
          padding 23px 0
          .link-doc
            display flex
            justify-content center
            flex-wrap wrap
            .link-doc-text
              font-size 14px
              color #FFFFFF
              height 20px
              line-height 20px
              margin-bottom 8px
              width 100%
              display flex
              justify-content center
            .link-doc-button
              background #E6ECF5
              border-radius 14px
              padding 4px 17px
              margin-top 14px
              display flex
              align-items center
              cursor pointer
              >i
                width 11px
                height 11px
                background url(../../common/image/icon/wendang.png) no-repeat center
                background-size 11px 11px
                display inline-block
                margin-right 5px
        .notice-list
          font-size 14px
          color #4a4a4a
          letter-spacing 0
          list-style disc
          .notice-item
            margin 20px
    .content-right
      width 50%
      height 100%
      float right
      .content-right-box
        padding 25px 0 25px 15px
      .right-item
        display flex
        align-items center
        justify-content center
        background #f4faff
        border-radius 1px
        margin-bottom 35px
        border 1px solid #E5E9F0
        &:hover
          bottom 6px
          box-shadow 0 0 18px 0 #e4e7ed
        .consume-content
          width 100%
          display flex
          .compute
            padding 50px 10px 32px 78px
          .storage
            padding 50px 0px 32px 30px
          .consume-content-item
            width 50%
            .consume-img
              width 80px
              height 80px
            .consume-item-count
              font-size 16px
              color #2D323B
              padding 47px 0 9px 0
              height 42px
              line-height 42px
              box-sizing content-box
              font-weight 600
              >span
                font-size 30px
                color #001400
            .consume-item-count-used
              font-size 14px
              height 20px
              line-height 20px
              box-sizing content-box
              padding-bottom 22px
              color #8D9091
            .consume-item-count-link
              font-size 12px
              color #007AFF
              height 20px
              line-height 20px
              &:hover
                color #006BDD
                cursor pointer
      .social
        width 566px
        height 142px
        background url(../../common/image/social.png) no-repeat center
        background-size 566px 142px
        padding 56px 0 56px 208px
        box-sizing border-box
        font-size 20px
        color #FFFFFF
</style>
